package com.randev.snapgallery;

import java.io.File;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.randev.snap.MainMenuActivity;
import com.randev.snap.R;
import com.randev.snapcamera.CameraActivity;
import com.randev.snapconfig.Config;

public class GalleryActivity extends Activity {

	TextView tViewParentFolder;
	ListView lViewFolderList;
	boolean EXTERNAL_STORAGE_AVAILABLE = false;
	
	String[] folderList;
	private final String TAG = "GalleryActivity";
	private AlertDialog.Builder alertDialog;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.gallery);
		
		tViewParentFolder = (TextView) findViewById(R.id.tvParentFolder);
		lViewFolderList = (ListView) findViewById(R.id.lvFolderList);
		
		EXTERNAL_STORAGE_AVAILABLE = isExternalStorageWritable();
		alertDialog = new AlertDialog.Builder(GalleryActivity.this);

		setUpFileList();
		
		lViewFolderList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Bundle bundle = new Bundle();
				bundle.putString(Config.FOLDER_ID, folderList[arg2]);
				try {
					Intent imageGalleryIntent = new Intent(GalleryActivity.this, ImageGalleryActivity.class);
					imageGalleryIntent.putExtras(bundle);
					finish();
					startActivity(imageGalleryIntent);
				} catch (ActivityNotFoundException e) {
					Log.w(TAG, "Unable to start ImageGalleryActivity: " + e.toString());
				}
			}
		});
	}
	
	private void setUpFileList() {
		if (EXTERNAL_STORAGE_AVAILABLE) {
			File homePath = new File(Config.HOME_DIRECTORY);
			tViewParentFolder.setText(GalleryActivity.this.getString(R.string.gallery));
			folderList = getFileListForDirectory(homePath);
			
			if (folderList != null) {
				setListAdapter(folderList);
			} else {
				
		    	alertDialog.setTitle(GalleryActivity.this.getString(R.string.alert));
		    	TextView tViewWarning = new TextView(GalleryActivity.this);
		    	tViewWarning.setGravity(Gravity.CENTER_HORIZONTAL);
		    	tViewWarning.setHeight(90);
		    	alertDialog.setView(tViewWarning);
		    	tViewWarning.setText(GalleryActivity.this.getString(R.string.info_gallery_empty));
		    	alertDialog.setPositiveButton(GalleryActivity.this.getString(R.string.yes), new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						try {
							SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); 
							Editor editor = PreferenceManager.getDefaultSharedPreferences(getBaseContext()).edit();
							 
							String imageCount = prefs.getString("ImageCount", null);
							editor.putString("ImagesAvailable", imageCount);
							editor.commit();
							
							String folderId = prefs.getString("FolderId", null);
							int fId = Integer.parseInt(folderId);
				    		editor.putString("FolderId", String.valueOf(fId+1));
							editor.commit();
							
							Intent cameraIntent = new Intent(GalleryActivity.this, CameraActivity.class);
							finish();
							startActivity(cameraIntent);
			    		} catch (ActivityNotFoundException e) {
							Log.w(TAG, "Unable to start CameraActivity: " + e.toString());
						} catch (ClassCastException e) {
							Log.w(TAG, "Unable to set preferences to CameraActivity: ClassCastException " + e.toString());
						} catch (NullPointerException e) {
							Log.w(TAG, "Unable to set preferences to CameraActivity: NullPointerException " + e.toString());
						}
					}
				});
		    	alertDialog.setNegativeButton(GalleryActivity.this.getString(R.string.no), new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						try {
							Intent mainMenIntent = new Intent(GalleryActivity.this, MainMenuActivity.class);
							finish();
							startActivity(mainMenIntent);
			    		} catch (ActivityNotFoundException e) {
							Log.w(TAG, "Unable to start MainMenuActivity: " + e.toString());
						}
					}
				});
		    	alertDialog.show();
			}
		} else {
			Toast.makeText(GalleryActivity.this, "No sd card detected", Toast.LENGTH_SHORT).show();
    		
		}
	}

	private String[] getFileListForDirectory(File path) {
		if (path.exists()) {
			return path.list();
		}
		return null;
	}
	
	private void setListAdapter(String[] folderList) {
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
		  android.R.layout.simple_list_item_1, android.R.id.text1, folderList);
		lViewFolderList.setAdapter(adapter); 

		
	}
	
	private boolean isExternalStorageWritable() {
		boolean isMediaAvailable = false;
	    String state = Environment.getExternalStorageState();
	    if (Environment.MEDIA_MOUNTED.equals(state)) {
	    	isMediaAvailable =  true;
	    }
	    return isMediaAvailable;
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event)  {
	    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
	    	try {
		    	Intent  mainMenuIntent = new Intent(GalleryActivity.this, MainMenuActivity.class);
				finish();
				startActivity(mainMenuIntent);
	    	} catch (ActivityNotFoundException e) {
				Log.w(TAG, "Unable to start MainMenuActivity: " + e.toString());
			}
	    	return true;
	    }

	    return super.onKeyDown(keyCode, event);
	}
}
